<script lang="ts" setup>
import {
  addRouterApi,
  type BaseRouter,
  delRouterApi,
  getRouterAdminPageApi,
  getRouterListByIsAdminApi,
  initRouterDTO,
  type RouterDTO,
  type RouterVO,
  updateRouterApi
} from '@/request/api/router'
import { useGlobalDialog } from '@/hooks'
import { initPageDTO, initPageVO, type PageDTO, type PageVO, type ResultType } from '@/type/type'
import { useSystemStore } from '@/stores/system'
import { useUserStore } from '@/stores/user'
import { DialogEnum } from '@/enum'
import { useTemporaryStore } from '@/stores/temporary'

const { globalDialog } = useGlobalDialog()
const systemStore = useSystemStore()
const userStore = useUserStore()
const temporaryStore = useTemporaryStore()

// 表单实列
const formRef = ref<any>()
const data = ref<PageVO<RouterVO>>(initPageVO())
// 多选 id 集合
const ids = ref<any[]>([])
const isAdd = ref<boolean>(true)

// UI、Admin 父级路由 做下拉框数据
const uiParents = ref<BaseRouter[]>([])
const adminParents = ref<BaseRouter[]>([])

const getRouterListByIsAdmin = (isAdmin: boolean) => {
  getRouterListByIsAdminApi(isAdmin).then((res: ResultType<BaseRouter[]>) => {
    if (isAdmin) {
      adminParents.value = res.data
    } else {
      uiParents.value = res.data
    }
  })
}

// 初始化查询参数
const initQueryParams = () => {
  return {
    title: null,
    level: -1,
    isAdmin: -1,
    status: -1
  }
}

const refs = reactive({
  queryParamsForm: initQueryParams(),
  rules: {
    title: [{ required: true, message: '路由标题不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '路由name不能为空', trigger: 'blur' }],
    level: [{ required: true, message: '路由层级不能为空', trigger: 'blur' }],
    priority: [{ required: true, message: '次序不能为空', trigger: 'blur' }],
    isAdmin: [{ required: true, message: '是否为admin端不能为空', trigger: 'change' }],
    parentId: [{ required: true, message: '父路由ID不能为空', trigger: 'blur' }],
    isFrame: [{ required: true, message: '是否外链', trigger: 'blur' }],
    roleId: [{ required: true, message: '角色ID不能为空', trigger: 'blur' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
    isBar: [{ required: true, message: '路由类型不能为空', trigger: 'blur' }]
  }
})
const { queryParamsForm, rules } = toRefs(refs)
// 新增表单
const form = ref<RouterDTO>(initRouterDTO())
/** 查询列表 */
const page = reactive<PageDTO>(initPageDTO())

/** 查询列表 */
const getList = () => {
  page.param = setQueryParams()
  getRouterAdminPageApi(page).then((res: ResultType<PageVO<RouterVO>>) => {
    data.value = res.data
  })
}

// 新增数据层级、类型改变时修改表单值
const valueChange = () => {
  if (form.value.level === 2) {
    if (form.value.isAdmin) {
      form.value.parentId = adminParents.value[0].id
    } else {
      form.value.parentId = uiParents.value[0].id
    }
  } else {
    form.value.parentId = 0
  }
}

const setQueryParams = () => {
  const param: Record<string, any> = {}
  if (queryParamsForm.value.title != null) {
    param['title'] = queryParamsForm.value.title
  }
  if (queryParamsForm.value.isAdmin !== -1) {
    param['isAdmin'] = queryParamsForm.value.isAdmin
  }
  if (queryParamsForm.value.level !== -1) {
    param['level'] = queryParamsForm.value.level
  }
  if (queryParamsForm.value.status !== -1) {
    param['status'] = queryParamsForm.value.status
  }
  if (userStore.user.role) {
    param['roleId'] = userStore.user.role.id
  }
  return param
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParamsForm.value = initQueryParams()
  getList()
}

// 多选框选中数据
const handleSelectionChange = (selection: RouterVO[]) => {
  ids.value = selection.map((item) => item.id)
}

/** 新增、修改按钮操作 */
const handle = (add: boolean, row?: any) => {
  form.value = initRouterDTO()
  isAdd.value = add
  systemStore.dialog.router = true
  if (!add) {
    form.value = row
    temporaryStore.form.roleId = row.roleId
  }
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    if (form.value.id != undefined) {
      await globalDialog('确定修改 ID 为"' + form.value.id + '"的路由?').then((res: boolean) => {
        if (res) {
          updateRouterApi(form.value).then(() => {
            systemStore.dialog.router = false
            getList()
          })
        }
      })
    } else {
      addRouterApi(form.value).then(() => {
        systemStore.dialog.router = false
        getList()
      })
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (idArr: Array<number>) => {
  await globalDialog('确定删除 ID 为"' + idArr + '"的路由?').then((res: boolean) => {
    if (res) {
      delRouterApi(idArr).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

/** 启用停用按钮操作 */
const handleChangeStatus = async (id: number, status: boolean) => {
  const router: RouterDTO = initRouterDTO()
  router.id = id
  router.status = status
  const title = status ? '启用' : '停用'
  await globalDialog('确定' + title + ' ID 为"' + id + '"的路由?').then((res: boolean) => {
    if (res) {
      updateRouterApi(router).then((res: ResultType<boolean>) => {
        if (res.data) {
          getList()
        }
      })
    }
  })
}

onMounted(() => {
  getList()
  getRouterListByIsAdmin(true)
  getRouterListByIsAdmin(false)
})
</script>

<template>
  <el-container class="pt-5 gap-3" direction="vertical">
    <el-container class="pb-2 px-5" direction="vertical">
      <el-form ref="queryRef" :inline="true" :model="queryParamsForm">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="queryParamsForm.title"
            clearable
            placeholder="请输入标题"
            style="width: 120px"
            @keyup.enter="getList"
          />
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-select v-model="queryParamsForm.level" style="width: 80px" @keyup.enter="getList">
            <el-option :value="1" label="一级" />
            <el-option :value="2" label="二级" />
            <el-option :value="-1" label="无" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="isAdmin">
          <el-select v-model="queryParamsForm.isAdmin" style="width: 105px" @keyup.enter="getList">
            <el-option :value="0" label="UI" />
            <el-option :value="1" label="Admin" />
            <el-option :value="-1" label="无" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParamsForm.status" style="width: 100px" @keyup.enter="getList">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="未启用" />
            <el-option :value="-1" label="无" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="!px-2" plain type="primary" @click="getList">
            <SvgIcon message="搜索" name="search" />
          </el-button>
          <el-button class="!px-2" plain type="info" @click="resetQuery">
            <SvgIcon message="重置" name="refresh" />
          </el-button>
        </el-form-item>
      </el-form>
      <el-container class="gap-3 flex-wrap">
        <el-button class="!px-2 !m-0" plain type="primary" @click="handle(true)">
          <SvgIcon message="新增" name="add" />
        </el-button>
        <el-button
          :disabled="ids.length === 0"
          class="!px-2 !m-0"
          plain
          type="danger"
          @click="handleDelete(ids)"
        >
          <SvgIcon message="删除" name="delete" />
        </el-button>
      </el-container>
    </el-container>

    <el-table :data="data.list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" />
      <el-table-column label="标题" prop="title" width="120" />
      <el-table-column label="排序" prop="priority" sortable width="90" />
      <el-table-column label="权限" prop="role.name" width="150" />
      <el-table-column label="name" prop="name" width="180" />
      <el-table-column label="前缀" width="60">
        <template #default="scope">
          <SvgIcon :name="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column label="菜单?" prop="isBar" width="70" />
      <el-table-column label="外链?" prop="isFrame" width="70" />
      <el-table-column label="位置" prop="isAdmin" width="90">
        <template #default="scope">
          <el-tag :type="scope.row.isAdmin ? 'success' : 'info'">
            {{ scope.row.isAdmin ? 'Admin' : 'UI' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="路径" prop="path" show-overflow-tooltip />
      <el-table-column label="组件路径" prop="component" show-overflow-tooltip />
      <el-table-column label="状态" prop="status" width="70">
        <template #default="scope">
          <el-tag :type="scope.row.status ? 'success' : 'danger'">
            {{ scope.row.status ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="110">
        <template #default="scope">
          <el-button class="!p-2 !m-1" type="primary" @click="handle(false, scope.row)">
            <SvgIcon name="edit" />
          </el-button>
          <el-button
            v-if="!scope.row.status"
            class="!p-2 !m-1"
            type="success"
            @click="handleChangeStatus(scope.row.id, true)"
          >
            <SvgIcon name="refresh" />
          </el-button>
          <el-button
            v-else
            class="!p-2 !m-1"
            type="danger"
            @click="handleChangeStatus(scope.row.id, false)"
          >
            <SvgIcon name="error" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <PageBox
      :total="data.total"
      @update="
        (args: PageDTO) => {
          page.size = args.size
          page.current = args.current
          getList()
        }
      "
    />
    <!-- 添加或修改对话框 -->
    <DialogTemplate :attribute="DialogEnum.ROUTER">
      <template #default>
        <el-container class="gap-5" direction="vertical">
          <span class="text-center text-lg">{{ isAdd ? '添加路由' : '修改路由' }}</span>
          <el-form ref="formRef" :model="form" :rules="rules" class="flex flex-col gap-1">
            <el-container class="items-center flex-wrap gap-x-5">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入路由标题" />
              </el-form-item>
              <RoleForm @update="(value: number) => (form.roleId = value)" />
            </el-container>

            <el-container class="items-center flex-wrap gap-x-5">
              <el-form-item label="位置" prop="isAdmin">
                <el-radio-group v-model="form.isAdmin" @change="valueChange">
                  <el-radio :value="false">UI</el-radio>
                  <el-radio :value="true">Admin</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio :value="false">停用</el-radio>
                  <el-radio :value="true">启用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-container>
            <el-container class="items-center flex-wrap gap-x-5">
              <el-form-item label="菜单路由？" prop="isBar">
                <el-radio-group v-model="form.isBar">
                  <el-radio :value="false">否</el-radio>
                  <el-radio :value="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="层级" prop="isAdmin">
                <el-radio-group v-model="form.level" @change="valueChange">
                  <el-radio :value="1">一级</el-radio>
                  <el-radio :value="2">二级</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item class="min-w-80" label="上级路由" prop="parentId">
                <template v-if="form.isAdmin">
                  <el-select v-model="form.parentId" :disabled="form.level == 1">
                    <el-option
                      v-for="p in adminParents"
                      :key="p.id"
                      :label="p.title"
                      :value="p.id"
                    />
                    <el-option v-if="form.level == 1" :value="0" label="无" />
                  </el-select>
                </template>
                <template v-else>
                  <el-select v-model="form.parentId" :disabled="form.level == 1">
                    <el-option v-for="p in uiParents" :key="p.id" :label="p.title" :value="p.id" />
                    <el-option v-if="form.level == 1" :value="0" label="无" />
                  </el-select>
                </template>
              </el-form-item>
            </el-container>

            <el-container class="items-center flex-wrap gap-x-5">
              <el-form-item label="路由Name" prop="name">
                <el-input v-model="form.name" :maxlength="16" placeholder="路由 name" />
              </el-form-item>
              <el-form-item label="排序" prop="priority">
                <el-input-number v-model="form.priority" :max="100" :min="1" class="!w-32" />
              </el-form-item>
            </el-container>
            <el-container class="items-center flex-wrap gap-x-5">
              <el-form-item label="外链?" prop="isFrame">
                <el-radio-group v-model="form.isFrame">
                  <el-radio :value="false">否</el-radio>
                  <el-radio :value="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <SvgForm :value="form.icon" @getValue="(value: string) => (form.icon = value)" />
            </el-container>
            <el-form-item label="路径" prop="path">
              <el-input v-model="form.path" placeholder="路径" />
            </el-form-item>
            <el-form-item label="组件" prop="component">
              <el-input v-model="form.component" placeholder="路由组件路径" />
            </el-form-item>
          </el-form>
          <el-container class="justify-between">
            <el-button type="info" @click="systemStore.dialog.router = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </el-container>
        </el-container>
      </template>
    </DialogTemplate>
  </el-container>
</template>

<style lang="scss"></style>
